package com.contest.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.contest.constant.CommonsConstant;
import com.contest.entity.SysMenu;
import com.contest.entity.SysRole;
import com.contest.entity.UserInfo;
import com.contest.service.SysMenuService;
import com.contest.service.SysRoleService;
import com.contest.service.UserInfoService;
import com.contest.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 
 *
 * @author yfl
 * @email 617823298@qq.com
 * @date 2017-12-20 16:30:37
 */

@Controller
public class SysLoginController {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysMenuService sysMenuService;


    @PostMapping("/sysUser/sysLogin")
    @ResponseBody
    public R sysLogin(HttpServletRequest request,String loginName, String loginPwd){
        EntityWrapper<UserInfo> userEntityWrapper = new EntityWrapper<UserInfo>();
        userEntityWrapper.addFilter("fd_mobile={0} and fd_pwd={1} and fd_type={2}", loginName,MD5Utils.encrypt(loginPwd),0);
        UserInfo userInfo = userInfoService.selectOne(userEntityWrapper);
        if(userInfo != null){
            request.getSession().setAttribute(CommonsConstant.LOGIN_SESSION,userInfo);
            return R.ok();
        }else{
            return R.error("用户名或密码错误!");
        }
    }

    @RequestMapping("/sysUser/loginOut")
    @ResponseBody
    public R loginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute(CommonsConstant.LOGIN_SESSION);
        return R.ok();
    }

    @GetMapping("/index")
    public String index(HttpServletRequest request){
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute(CommonsConstant.LOGIN_SESSION);
        SysRole sysRole = sysRoleService.selectById(userInfo.getFdRoleId());
        List<MenuTree<SysMenu>> menus = sysMenuService.buildMenu(sysRole.getFdId());
        request.setAttribute(CommonsConstant.USER_MENU,menus);
        return "index";
    }

}
